import { contextBridge, ipcRenderer } from 'electron'

// 用于存储监听器引用，便于移除
const listeners = {
  progress: [],
  speed: [],
  complete: [],
  error: []
};

contextBridge.exposeInMainWorld('electronAPI', {
  send: (channel, data) => ipcRenderer.invoke(channel, data),
  on: (channel, func) => {
    ipcRenderer.on(channel, (event, ...args) => func(...args));
  },
  once: (channel, func) => {
    ipcRenderer.once(channel, (event, ...args) => func(...args));
  },
  // 启动下载
  startDownload: (id, url) => ipcRenderer.invoke('download:start', { id, url, name }),
  pauseDownload: (id) => ipcRenderer.invoke('download:pause', id),
  resumeDownload: (id) => ipcRenderer.invoke('download:resume', id),
  cancelDownload: (id) => ipcRenderer.invoke('download:cancel', id),
  // 动态注册事件监听（推荐）
  onDownloadProgress: (callback) => {
    const handler = (_, data) => callback(data);
    ipcRenderer.on('download:progress', handler);
    listeners.progress.push({ callback, handler });
    return () => {
      ipcRenderer.removeListener('download:progress', handler);
      listeners.progress = listeners.progress.filter(l => l.callback !== callback);
    };
  },
  onDownloadSpeed: (callback) => {
    const handler = (_, data) => callback(data);
    ipcRenderer.on('download:speed', handler);
    listeners.speed.push({ callback, handler });
    return () => {
      ipcRenderer.removeListener('download:speed', handler);
      listeners.speed = listeners.speed.filter(l => l.callback !== callback);
    };
  },
  onDownloadComplete: (callback) => {
    const handler = (_, data) => callback(data);
    ipcRenderer.on('download:complete', handler);
    listeners.complete.push({ callback, handler });
    return () => {
      ipcRenderer.removeListener('download:complete', handler);
      listeners.complete = listeners.complete.filter(l => l.callback !== callback);
    };
  },
  onDownloadError: (callback) => {
    const handler = (_, data) => callback(data);
    ipcRenderer.on('download:error', handler);
    listeners.error.push({ callback, handler });
    return () => {
      ipcRenderer.removeListener('download:error', handler);
      listeners.error = listeners.error.filter(l => l.callback !== callback);
    };
  },
  // 调试：查看当前监听数
  getListenerCount: () => ({
    progress: listeners.progress.length,
    speed: listeners.speed.length,
    complete: listeners.complete.length,
    error: listeners.error.length,
  })
});